package org.anderground.app.storage.db;

import java.io.IOException;

import org.anderground.modules.storage.AbstractWriter;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author Eldar Abusalimov
 * @param <T>
 *            data type
 */
public abstract class AbstractDbWriter<T> extends
		AbstractWriter<T, SQLiteDatabase> {

	private final SQLiteOpenHelper openHelper;
	private SQLiteDatabase db;

	/**
	 * Constructs a new {@link AbstractDbWriter} that uses the specified
	 * {@link SQLiteOpenHelper} to open the database for the future operations.
	 * 
	 * @param openHelper
	 *            the {@link SQLiteOpenHelper} to use for opening the database
	 *            on {@link #write(Object)} call; the database will be closed
	 *            after writing competes
	 */
	public AbstractDbWriter(SQLiteOpenHelper openHelper) {
		if (openHelper == null) {
			throw new IllegalArgumentException("db openHelper cannot be null");
		}
		this.openHelper = openHelper;
	}

	/**
	 * Constructs a new {@link AbstractDbWriter} that uses the specified
	 * {@link SQLiteDatabase} for the future operations.
	 * 
	 * @param db
	 *            the {@link SQLiteDatabase} to use for the future writing; You
	 *            should take care of database closing
	 */
	public AbstractDbWriter(SQLiteDatabase db) {
		if (db == null) {
			throw new IllegalArgumentException("db cannot be null");
		}
		this.openHelper = null;
		this.db = db;
	}

	@Override
	public final void closeIO(SQLiteDatabase io) throws IOException {
		io.close();
	}

	@Override
	public final SQLiteDatabase openIO() throws IOException {
		if (openHelper != null) {
			db = openHelper.getWritableDatabase();
		}
		return db;
	}

	@Override
	public final boolean shouldCloseIOAfterComplete() {
		return openHelper != null;
	}

	@Override
	protected final void onPreExecute(SQLiteDatabase io) {
		io.beginTransaction();
	}

	@Override
	protected final void onSuccess(SQLiteDatabase io) {
		io.setTransactionSuccessful();
	}

	@Override
	protected final void onPostExecute(SQLiteDatabase io) {
		io.endTransaction();
	}

}
